package com.ks.test.app;

import com.sun.tools.attach.VirtualMachine;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class AttachMain {

    /**
     * 加载 tools.jar
     *
     * @throws NoSuchMethodException
     * @throws MalformedURLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private static void prepareAttach() throws NoSuchMethodException, MalformedURLException, InvocationTargetException, IllegalAccessException {
        String binPath = System.getProperty("sun.boot.library.path");
        // remove jre/bin, replace with lib
        String libPath = binPath.substring(0, binPath.length() - 7) + "lib";
        URLClassLoader loader = (URLClassLoader) AttachMain.class.getClassLoader();
        Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        addURLMethod.setAccessible(true);
        File toolsJar = new File(libPath + "/tools.jar");
        if (!toolsJar.exists()) {
            throw new RuntimeException(toolsJar.getAbsolutePath() + " does not exist");
        }
        addURLMethod.invoke(loader, new File(libPath + "/tools.jar").toURI().toURL());
    }

    public static void main(String[] args) {

        String pid = args[0];
        String agentPath = args[1];

        File agentFile = new File(agentPath);

        if (!agentFile.exists()) {
            System.out.println("Agent not exist!");
            return;
        }

        try {

            prepareAttach();

            VirtualMachine virtualMachine = VirtualMachine.attach(pid);
            virtualMachine.loadAgent(agentFile.getAbsolutePath());

            virtualMachine.detach();

            System.out.println("attach success!");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // attach ok
    }
}
